package com.tnovoselec.android.feed.handler;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.tnovoselec.android.favorites.entity.MeteoFavoritesDto;



public class WeatherCityParser extends DefaultHandler {

    private StringBuilder buffer;
    private List<MeteoFavoritesDto> weather;
    private MeteoFavoritesDto tempWeather;

    private final static String TAG_ITEM = "item";
    private final static String TAG_TITLE = "title";
    private final static String TAG_URL = "url";
    private final static String TAG_ID = "id";

    private boolean inItem = false;
    private boolean inTitle = false;
    private boolean inUrl = false;
    private boolean inId = false;

    private int position = 0;

    @Override
    public void startDocument() throws SAXException {
	super.startDocument();
	weather = new ArrayList<MeteoFavoritesDto>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
	buffer = new StringBuilder("");

	if (localName.equalsIgnoreCase(TAG_ITEM)) {
	    inItem = true;
	    tempWeather = new MeteoFavoritesDto();
	} else if (localName.equalsIgnoreCase(TAG_TITLE)) {
	    inTitle = true;
	} else if (localName.equalsIgnoreCase(TAG_URL)) {
	    inUrl = true;
	} else if (localName.equalsIgnoreCase(TAG_ID)) {
	    inId = true;
	}
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
	if (inItem) {
	    if (inTitle) {
		tempWeather.setTitle(buffer.toString());
	    } else if (inUrl) {
		tempWeather.setUrl(buffer.toString());
	    } else if (inId) {
		tempWeather.setCityId(buffer.toString());
	    }
	}

	if (localName.equalsIgnoreCase(TAG_ITEM)) {
	    inItem = false;
	    tempWeather.setPosition(position++);
	    weather.add(tempWeather);
	} else if (localName.equalsIgnoreCase(TAG_TITLE)) {
	    inTitle = false;
	} else if (localName.equalsIgnoreCase(TAG_URL)) {
	    inUrl = false;
	} else if (localName.equalsIgnoreCase(TAG_ID)) {
	    inId = false;
	}
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
	buffer.append(String.valueOf(ch, start, length));
    }

    /**
     * Method used to get the all the weather data
     * 
     * @return List containing weather data
     */
    public List<MeteoFavoritesDto> getWeather() {
	return weather;
    }

}
